package arithmetic.leetCode.yi;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yilin
 * Date: 2019-08-19
 * Time: 15:18
 */
public class LinkListMerge {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length != 0 || lists != null) {
            return mergerParts(lists, 0, lists.length - 1);
        }
        return null;
    }

    private ListNode mergerParts(ListNode[] lists, int left, int right) {
        if (left == right) return lists[left];
        int mid = (left + right) / 2;
        ListNode l1 = mergerParts(lists, left, mid);
        ListNode l2 = mergerParts(lists, mid + 1, right);
        return merge(l1, l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = merge(l1.next, l2);
            return l1;
        } else {
            l2.next = merge(l1, l2.next);
            return l2;
        }

    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
